package edu.tces482.plms;
import java.math.BigInteger;

import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class SerialTest {

	private static final boolean DEBUG_ENABLE = true;

	private static final String EXPECTED_PORT_NAME = "/dev/tty.usbserial-A9014OBQ";

	public static void main(String[] args) 
	{
		boolean portAvailable = false;

		while (!portAvailable)
		{
			String[] portNames = SerialPortList.getPortNames();
			for(int i = 0; i < portNames.length; i++)
			{
				System.out.print(portNames[i]);
				if (EXPECTED_PORT_NAME.equals(portNames[i]))
				{
					portAvailable = true;
					if (DEBUG_ENABLE) 
					{
						System.out.println("Found " + EXPECTED_PORT_NAME + "!");
					}
					break;
				}
			}
		}

		// TODO Handle messages from multiple nodes
		
		SerialPort serialPort = new SerialPort(EXPECTED_PORT_NAME);
		try {
			StringBuilder buffer = new StringBuilder();
			String next, line, label, value;
			boolean msg_started = false;
			int endOfLine = -1;
			BigInteger id = null;
			int status = 0;

			serialPort.openPort();//Open serial port
			serialPort.setParams(9600, 8, 1, 0);//Set params.

			while (serialPort.isOpened()) 
			{
				line = null;
				while (line == null) 
				{
					next = serialPort.readString();
					if (next != null) 
					{
						buffer.append(next);
					}

					endOfLine = buffer.indexOf("\n");
					if (endOfLine > -1) 
					{
						line = buffer.substring(0, endOfLine);
						buffer.delete(0, endOfLine + 1);
					}
				}

				if (line.length() > 0) 
				{
					label = null;
					value = null;
					
					String [] split = line.toString().split("=");
					label = split[0];
					if (split.length > 1) {
						value = split[1];
					}

					if ("s".equals(label)) 
					{
						if (msg_started) {
							// TODO Handle error condition
							System.out.println("msg_error: Already received start");
						} else {
							msg_started = true;
						}
					}
					else if (label.equals("id")) 
					{
						if (msg_started)
						{
							byte [] id_bytes = SerialTest.hexStringToByteArray(value);
							id = new BigInteger(1, id_bytes);
						} 
						else 
						{
							// TODO Handle error condition
							System.out.println("msg_error: Id received without start");
						}
					} 
					else if (label.equals("status")) 
					{
						if (msg_started)
						{
							status = Integer.parseInt(value);
						} 
						else 
						{
							// TODO Handle error condition
							System.out.println("msg_error: Status received without start ");
						}	
					}
					else if ("e".equals(label))
					{
						if (msg_started)
						{
							if (DEBUG_ENABLE) 
							{
								System.out.println("ID: " + id + " (0x" + id.toString(16) + ")");
								System.out.println("STATUS: " + status + "\n");
							}
	
							// TODO Update database
							
							id = null;
							status = -1;
							msg_started = false;
						} 
						else 
						{
							// TODO Handle error condition
							System.out.println("msg_error: End received without start");
						}
					}
				}
			}

			serialPort.closePort();//Close serial port
		}
		catch (SerialPortException ex) 
		{
			System.out.println(ex);
		}
	}

	public static byte[] hexStringToByteArray(String s) {
		int len = s.length();
		byte[] data = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
					+ Character.digit(s.charAt(i+1), 16));
		}
		return data;
	}
}
